package com.movie.controller;

import com.movie.entity.Review;
import com.movie.entity.User;
import com.movie.mapper.UserMapper;
// import com.movie.security.UserDetailsImpl; // 假设有 UserDetails 实现类
import com.movie.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import com.movie.config.CustomUserDetails; // 导入 CustomUserDetails
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.http.HttpStatus;

import java.util.List;

@RestController
@RequestMapping("/api") // 根路径改为 /api
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true") // 添加跨域配置
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private UserMapper userMapper;

    // 获取某部电影的所有评论
    @GetMapping("/movies/{movieId}/reviews")
    public ResponseEntity<List<Review>> getMovieReviews(@PathVariable Long movieId) {
        List<Review> reviews = reviewService.getReviewsByMovieId(movieId);
        return ResponseEntity.ok(reviews);
    }

    // 创建新评论 (修改后)
    @PostMapping("/movies/{movieId}/reviews")
    @PreAuthorize("hasRole('USER')") // 只有普通用户能创建
    public ResponseEntity<Review> createMovieReview(
            @PathVariable Long movieId, 
            @RequestBody Review review, 
            @AuthenticationPrincipal CustomUserDetails currentUser) {
        
        if (currentUser == null) {
            // 虽然 @PreAuthorize 应该阻止未登录用户，但加个保险
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        review.setMovieId(movieId);
        review.setUserId(currentUser.getId()); // 从认证信息设置 userId
        // review.setReviewTime(LocalDateTime.now()); // Service 层会设置时间
        
        Review createdReview = reviewService.createReview(review);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdReview);
        // 注意：如果 createReview 抛出 DuplicateReviewException，会被 @ResponseStatus 处理返回 409
    }

    // 获取当前用户的所有评论
    @GetMapping("/reviews/my")
    @PreAuthorize("isAuthenticated()")
    public ResponseEntity<List<Review>> getMyReviews() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        Long userId;
        if (principal instanceof UserDetails) {
            String username = ((UserDetails) principal).getUsername();
            User user = userMapper.findByUsername(username);
            if (user != null) {
                userId = user.getId();
            } else {
                throw new RuntimeException("Authenticated user not found in database: " + username);
            }
        } else {
            throw new RuntimeException("Cannot determine userId from principal: " + principal);
        }
        List<Review> reviews = reviewService.getReviewsByUserId(userId);
        return ResponseEntity.ok(reviews);
    }

    // 更新评论
    @PutMapping("/reviews/{reviewId}")
    @PreAuthorize("isAuthenticated()") // 确保用户已登录，具体权限在 Service 层检查
    public ResponseEntity<Review> updateMovieReview(
            @PathVariable Long reviewId,
            @RequestBody Review reviewDetails, // 只包含 rating 和 comment
            @AuthenticationPrincipal CustomUserDetails currentUser) {
        
        if (currentUser == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        // Service 层会进行权限检查 (currentUserId)
        Review updatedReview = reviewService.updateReview(reviewId, reviewDetails, currentUser.getId());
        return ResponseEntity.ok(updatedReview);
    }

    // 删除评论和查看他人评论的接口已移至 AdminReviewController 或被移除
} 